import {
  DBTableAtom,
  Header,
  PreviewAdapter,
  PreviewParamFormAtom,
  PreviewTreeAtom,
  TableRefTableAtom,
  TemplateTreeAtom,
} from "@/components";
import { createAtom, useStore } from "@/util/hooks";
import { Button, Input, Message, Space } from "@arco-design/web-react";
import { FolderOpen, Refresh } from "@icon-park/react";
import { PreviewHeaderStore } from "./inteface";
import { preview } from "@/api";
import { ResultUtil } from "@/util";
import _ from "lodash";
import { IconPlayArrow } from "@arco-design/web-react/icon";

export const PreviewHeaderAtom = createAtom<PreviewHeaderStore>({
  baseUrl: "",
});

export const PreviewHeader = () => {
  const store = useStore(PreviewHeaderAtom);
  const dbStore = useStore(DBTableAtom);
  const tableRefStore = useStore(TableRefTableAtom);
  const templateTreeStore = useStore(TemplateTreeAtom);
  const previewTreeStore = useStore(PreviewTreeAtom);
  const previewParamStore = useStore(PreviewParamFormAtom);

  const url = store.value.baseUrl;
  const { originDataList: data, selectedRecord } = previewTreeStore.value;

  async function handleRefresh() {
    const selectedDB = dbStore.value.selected;
    if (!selectedDB) {
      Message.error("请选择数据源");
      return;
    }
    const { selectedRowKeys: tableSelected, data: tableRefData } =
      tableRefStore.value;
    if (!tableSelected) {
      Message.error("请选择表");
      return;
    }

    const { checkedKeys, originData: templateData } = templateTreeStore.value;
    if (_.isEmpty(checkedKeys)) {
      Message.error("请选择模版");
      return;
    }

    const tableRefs = tableRefData.filter((k) =>
      tableSelected.includes(k.tableName)
    );

    const templateFileIds = templateData
      .filter((k) => checkedKeys!.includes(k.id) && !k.directory)
      .map((k) => k.id);

    if (!templateFileIds) {
      Message.error("请选择模版文件");
      return;
    }

    const res = await preview.call({
      dbId: selectedDB.id!,
      tableRefs,
      templateFileIds,
      params: previewParamStore.value.data || {},
    });
    if (!ResultUtil.showError(res)) {
      return;
    }

    const data = res.data;
    const treeData = PreviewAdapter.toTreeData(data.data);
    store.updateStore({
      baseUrl: data.baseUrl,
    });
    previewTreeStore.updateStore({
      data: [...treeData],
      originDataList: data.data,
    });
    if (previewTreeStore.value.selectedKey) {
      const selectedRecord = _.findLast(
        data.data,
        (k) => k.absoluteUrl === previewTreeStore.value.selectedKey
      );
      if (selectedRecord) {
        previewTreeStore.updateStore({
          selectedRecord,
        });
      } else {
        previewTreeStore.updateStore({
          selectedKey: undefined,
          selectedRecord: undefined,
        });
      }
    }
  }

  async function handleConfirm() {
    const res = await preview.generate(store.value.baseUrl!, data);
    ResultUtil.showResult(res);
  }

  const title = (
    <>
      <Input
        size="small"
        value={store.value.baseUrl}
        placeholder="项目根目录"
        onChange={(value) => store.updateStore({ baseUrl: value })}
      />
    </>
  );

  return (
    <Header
      title={title}
      extra={
        <Space>
          <Button title="刷新" icon={<Refresh />} onClick={handleRefresh} />
          <Button
            title="应用"
            icon={<IconPlayArrow />}
            disabled={!(data && data.length > 0)}
            onClick={handleConfirm}
          />
          <Button
            title="打开对应目录"
            icon={<FolderOpen />}
            disabled={!url}
            onClick={() => {
              if (selectedRecord) {
                const newUrl = `${url}/${selectedRecord.codeBaseUrl || ""}/${
                  selectedRecord.packageUrl || ""
                }`.replaceAll("//", "/");
                preview.openFolder(newUrl);
              } else {
                preview.openFolder(url!);
              }
            }}
          />
        </Space>
      }
    ></Header>
  );
};
